﻿package com.urbansquall.echo
{
	import flash.media.Sound;
	import flash.media.SoundChannel;
	import flash.media.SoundTransform;
	
	/**
	 * Allows you to control the volume of several sounds at once.
	 * @author Marshall Powers
	 */
	public class SoundGroup 
	{	
		private var m_volume : Number;
		private var m_children : Array; /* ChannelWrapper */
		
		public function SoundGroup() 
		{
			m_volume = 1.0;
			m_children = new Array();
		}
		
		public function addChild(a_wrapper : ChannelWrapper) : void
		{
			m_children.push(a_wrapper);
			a_wrapper.parent = this;
			a_wrapper.updateChannelVolume();
			
			a_wrapper.addEventListener(WrapperEvent.SOUND_COMPLETE, childPlaybackEnded);
			a_wrapper.addEventListener(WrapperEvent.SOUND_STOPPED, childPlaybackEnded);
		}
		
		public function removeChild(a_wrapper : ChannelWrapper) : void
		{
			var idx : int = m_children.indexOf(a_wrapper);
			if (idx == -1)
			{
				throw new Error("SoundGroup:removeChild. Object must be a child of the Group");
			}
			else
			{
				m_children.splice(idx, 1);
				a_wrapper.parent = null
				a_wrapper.removeEventListener(WrapperEvent.SOUND_COMPLETE, childPlaybackEnded);
				a_wrapper.removeEventListener(WrapperEvent.SOUND_STOPPED, childPlaybackEnded);
			}
		}
		
		private function childPlaybackEnded(a_event : WrapperEvent) : void
		{
			removeChild(a_event.channelWrapper)
		}
		
		public function get numChildren() : int
		{
			return m_children.length;
		}
		
		public function stopAll() : void
		{
			var tmp : Array = m_children.slice()
			for each(var wrapper : ChannelWrapper in tmp)
			{
				wrapper.stop();
			}
		}
		
		public function dispose() : void
		{	
			stopAll()
			m_children = null;
		}
		
		public function get volume() : Number
		{
			return m_volume;
		}
		
		public function set volume (a_volume : Number) : void
		{
			m_volume = a_volume;
			for each(var cw : ChannelWrapper in m_children)
			{
				cw.updateChannelVolume();
			}
		}
	}
	
}